package me.firstapp.service.bbs.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.utils.MD5Utils;
import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.bbs.Member;
import me.firstapp.module.bbs.PointAccount;
import me.firstapp.module.bbs.SystemNotification;
import me.firstapp.module.shop.ShoppingCart;
import me.firstapp.repository.bbs.MemberRepository;
import me.firstapp.repository.bbs.PointAccountRepository;
import me.firstapp.repository.bbs.SystemNotificationRepository;
import me.firstapp.repository.shop.ShoppingCartRepository;
import me.firstapp.service.bbs.MemberService;

@Service
public class MemberServiceImpl implements MemberService {

	@Autowired
	private MemberRepository memberRepository;

	@Autowired
	private PointAccountRepository pointAccountRepository;

	@Autowired
	private ShoppingCartRepository shoppingCartRepository;

	@Autowired
	private SystemNotificationRepository systemNotificationRepository;

	@Override
	public Member findMemberByName(String name, Long apiClientId) {
		return memberRepository.findMemberByName(name, apiClientId);
	}

	@Override
	public Member findMemberByEmail(String email, Long apiClientId) {
		return memberRepository.findMemberByEmail(email, apiClientId);
	}

	@Override
	public Member findMemberByMobile(String mobile, Long apiClientId) {
		return memberRepository.findMemberByMobile(mobile, apiClientId);
	}

	@Override
	public Member addMember(String name, String password, String avatar, String email, String mobile, String signature,
			String url, Long apiClientId) {
		// 合法性验证
		if (StrUtils.isNULL(name)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "昵称");
		}
		if (!StrUtils.isUserName(name)) {
			throw new ServiceException(StatusHouse.USER_NAME_FORMAT_WRONG);
		}
		if (StrUtils.isNULL(password)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "密码");
		}
		if (StrUtils.isNULL(email) && StrUtils.isNULL(mobile)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "手机号或邮箱");
		}
		Member member = null;
		if (StrUtils.isNotNULL(mobile)) {
			if (!StrUtils.isMobile(mobile)) {
				throw new ServiceException(StatusHouse.MOBILE_FORMAT_WRONG);
			}
			member = memberRepository.findMemberByMobile(mobile, apiClientId);
			if (member != null) {
				throw new ServiceException(StatusHouse.MOBILE_IS_EXIST);
			}
		}
		if (StrUtils.isNotNULL(email)) {
			if (!StrUtils.isMail(email)) {
				throw new ServiceException(StatusHouse.EMAIL_FORMAT_WRONG);
			}
		}
		member = memberRepository.findMemberByEmail(email, apiClientId);
		if (member != null) {
			throw new ServiceException(StatusHouse.EMAIL_IS_EXIST);
		}
		member = memberRepository.findMemberByName(name, apiClientId);
		if (member != null) {
			throw new ServiceException(StatusHouse.NAME_IS_EXIST);
		}

		// 创建新用户
		member = new Member();
		member.setName(name);
		member.setPassword(MD5Utils.generate(password));
		member.setAvatar(avatar);
		member.setEmail(email);
		member.setMobile(mobile);
		member.setSignature(signature);
		member.setUrl(url);
		member.setApiClientId(apiClientId);
		member.setRegisterTime(Calendar.getInstance().getTime());
		memberRepository.save(member);

		// 创建积分账户
		PointAccount pointAccount = new PointAccount();
		pointAccount.setMember(member);
		pointAccount.setCurrentValue(0.00);
		pointAccount.setSalt(MD5Utils.generate(pointAccount.getCurrentValue().toString()));
		pointAccount.setHasPassword(0);
		pointAccount.setApiClientId(apiClientId);
		pointAccountRepository.save(pointAccount);

		// 创建购物车
		ShoppingCart shoppingCart = new ShoppingCart();
		shoppingCart.setMember(member);
		shoppingCart.setCounts(0);
		shoppingCart.setValue(0D);
		shoppingCart.setApiClientId(apiClientId);
		shoppingCartRepository.save(shoppingCart);

		// 注册成功系统通知
		try {
			SystemNotification systemNotification = new SystemNotification();
			systemNotification.setContent("恭喜你成功注册！");
			systemNotification.setIsRead(0);
			systemNotification.setNotifyTime(new Date());
			systemNotification.setToMember(member);
			systemNotification.setApiClientId(apiClientId);
			systemNotificationRepository.save(systemNotification);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return member;
	}

	@Override
	public Member findMemberById(Long id, Long apiClientId) {
		if (id == null) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "id");
		}
		return (Member) memberRepository.findMemberById(id, apiClientId);
	}

	@Override
	public Member executeLogin(String mobile, String email, String name, String password, Long apiClientId) {

		if (StrUtils.isNULL(password)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "密码");
		}
		if (StrUtils.isNULL(mobile) && StrUtils.isNULL(email) && StrUtils.isNULL(password)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "手机号或用户名或邮箱");
		}
		Member member = null;
		if (StrUtils.isNotNULL(mobile)) {
			if (!StrUtils.isMobile(mobile)) {
				throw new ServiceException(StatusHouse.MOBILE_FORMAT_WRONG);
			}
			member = memberRepository.findMemberByMobile(mobile, apiClientId);

		}
		if (StrUtils.isNotNULL(email)) {
			if (!StrUtils.isMail(email)) {
				throw new ServiceException(StatusHouse.EMAIL_FORMAT_WRONG);
			}
			member = memberRepository.findMemberByEmail(email, apiClientId);
		}
		if (StrUtils.isNotNULL(name)) {
			member = memberRepository.findMemberByName(name, apiClientId);
		}
		if (member == null) {
			throw new ServiceException(StatusHouse.MEMBER_NOT_FOUND);
		}
		if (member.getStatus() == 0) {
			throw new ServiceException(StatusHouse.MEMBER_NOT_USE);
		}

		if (!MD5Utils.verify(password, member.getPassword())) {
			throw new ServiceException(StatusHouse.PASSWORD_IS_WRONG);
		}

		return member;
	}

	public Member updateMemberInfo(Long memberId, String avatar, String url, String signature, Integer status,
			Long apiClientId) {
		if (memberId == null) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "用户id");
		}
		Member member = (Member) memberRepository.findMemberById(memberId, apiClientId);
		if (member == null) {
			throw new ServiceException(StatusHouse.MEMBER_NOT_FOUND);
		}
		if (StrUtils.isNotNULL(avatar)) {
			member.setAvatar(avatar);
		}
		if (StrUtils.isNotNULL(url)) {
			member.setUrl(url);
		}
		if (StrUtils.isNotNULL(signature)) {
			member.setSignature(signature);
		}
		if (status != null) {
			member.setStatus(status);
		}
		memberRepository.update(member);
		return member;
	}

	@Override
	public Member updateMemberPassword(Long memberId, String oldPassword, String newPassword, Long apiClientId) {
		if (memberId == null) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "用户id");
		}
		if (StrUtils.isNULL(oldPassword)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "旧密码");
		}
		if (StrUtils.isNULL(newPassword)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "新密码");
		}
		Member member = (Member) memberRepository.findMemberById(memberId, apiClientId);
		if (member == null) {
			throw new ServiceException(StatusHouse.MEMBER_NOT_FOUND);
		}
		boolean right = MD5Utils.verify(oldPassword, member.getPassword());
		if (!right) {
			throw new ServiceException(StatusHouse.PASSWORD_IS_WRONG);
		}

		member.setPassword(MD5Utils.generate(newPassword));
		memberRepository.update(member);

		return member;
	}

	@Override
	public Page<Member> findMemberPage(Integer pageNo, Integer pageSize, Map<String, Object> searchParams,
			String sortParam, String sortType, Date startTime, Date endTime, Long apiClientId) {
		return memberRepository.findMemberPage(pageNo, pageSize, searchParams, sortParam, sortType, startTime, endTime,
				apiClientId);
	}

	@Override
	public Member executeResetPassword(String email, String newPassword, Long apiClientId) {
		if (StrUtils.isNULL(email)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "邮箱");
		}
		if (StrUtils.isNULL(newPassword)) {
			throw new ServiceException(StatusHouse.COMMON_STATUS_PARAM_REQUIRED_ERROR, "密码");
		}
		if (!StrUtils.isMail(email)) {
			throw new ServiceException(StatusHouse.EMAIL_FORMAT_WRONG);
		}
		Member member = memberRepository.findMemberByEmail(email, apiClientId);
		if (member == null) {
			throw new ServiceException(StatusHouse.MEMBER_NOT_FOUND);
		}
		member.setPassword(MD5Utils.generate(newPassword));
		memberRepository.update(member);
		return member;
	}

}
